package com.tcj.myprogram.memorialday;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.tcj.myprogram.memorialday.myview.MyView;

/**
 * Base Activity. All activity must extends this.
 * 
 * @author tsengchienjung
 */
public class BaseActivity extends Activity {
	public final static String TAG_BASE = "MemorialDay-";
	public final static String TAG = "MemorialDay-BaseActivity";

	/**
	 * 在Activity中的資料KEY->對應View的Class名檔
	 */
	public final static String INTENT_KEY_VIEW_NAME = "view_name";

	/**
	 * Handle的what使用，收到後->開始轉圈圈
	 */
	public final static int HANDLE_WHAT_START_PROGRESS = 1;

	/**
	 * Handle的what使用，收到後->停止轉圈圈
	 */
	public final static int HANDLE_WHAT_STOP_PROGRESS = 2;

	/**
	 * Handle的what使用，收到後->顯示Toast
	 */
	public final static int HANDLE_WHAT_SHOW_TOAST = 102;

	/**
	 * Handle的what使用，收到後->顯示Alert
	 */
	public final static int HANDLE_WHAT_SHOW_ALERT = 104;

	/**
	 * Handle的what使用，收到後->顯示Alert，使用者點選後結束Activity
	 */
	public final static int HANDLE_WHAT_SHOW_ALERT_WITH_FINISH = 103;

	// My AD id
	public final static String AD_UNIT_ID = "ca-app-pub-4961926714209493/5655212760";

	// View name
	public final static String MY_VIEW_MAIN = "MainMyView";

	// Preference使用
	public final static String PREFERENCE = "Preference";

	protected MyView myView = null;

	/**
	 * 轉圈圈
	 */
	private ProgressDialog progressDialog;

	/**
	 * Application preference
	 */
	private static SharedPreferences settings;

	/**
	 * Handle，跑在主執行上（從其他執行緒上回到主執行緒中的其中一種方法）
	 */
	public Handler myHandly = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case R.string.alert_with_SocketTimeoutException:
			case R.string.alert_with_UnknownHostException:
			case R.string.alert_with_IOException:
			case R.string.alert_with_Exception:
				// 顯示Alert
				showAlert(getText(msg.what).toString());
				break;
			case HANDLE_WHAT_START_PROGRESS:
				// 顯示轉圈圈
				showProgressDialog();
				break;
			case HANDLE_WHAT_STOP_PROGRESS:
				// 轉圈圈結束
				hideProgressDialog();
				break;
			case HANDLE_WHAT_SHOW_ALERT:
				// 顯示Alert
				showAlert(msg.obj.toString());
				break;
			case HANDLE_WHAT_SHOW_ALERT_WITH_FINISH:
				// 顯示Alert後，結束Activity
				showAlertWithFinish(msg.obj.toString());
				break;
			case HANDLE_WHAT_SHOW_TOAST:
				// 顯示Toast
				showToastMessage(msg.obj.toString(), Toast.LENGTH_SHORT);
				break;
			default:
				if (null != myView) {
					// 只要myView不是null，將回到myView去處理
					myView.doHandleMessage(msg);
				}
				break;
			}

		}
	};

	public Handler getMyHandly() {
		return myHandly;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// 初始化一次就夠了
		if (null == settings) {
			settings = getSharedPreferences(PREFERENCE, Context.MODE_PRIVATE);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (null != myView) {
			myView.doOnDestroy();
		}
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (null != myView) {
			myView.doOnPause();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (null != myView) {
			myView.doOnResume();
		}

	}

	@Override
	protected void onStart() {
		super.onStart();
		if (null != myView) {
			myView.doOnStart();
		}
	}

	/**
	 * 廣告設定
	 */
	public void setAd() {
		if (ConnectionResult.SUCCESS == GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)
				|| ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED == GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)) {
			if (null != myView && myView.isShowAD()) {
				LinearLayout adLinearLayout = (LinearLayout) findViewById(R.id.adMob);
				AdView adView = new AdView(this);
				adView.setAdUnitId(AD_UNIT_ID);
				adView.setAdSize(AdSize.SMART_BANNER);
				adLinearLayout.addView(adView);
				AdRequest request = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
				// SONY XPERIA
						.addTestDevice("586E5DEFD54A51AA48BA7DA260CD36D2")
						// W1011A
						.addTestDevice("D7F738D38E2EF82EA898165D00673490").build();
				adView.loadAd(request);
			}
		}
	}

	/**
	 * if myView will do something to stop call
	 * super.onConfigurationChanged(newConfig) method, use "return" to stop
	 * calling.
	 */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (null != myView) {
			myView.doOnConfigurationChanged(newConfig);
		}
	}

	@Override
	public void setRequestedOrientation(int requestedOrientation) {
		if (null != myView) {
			myView.doSetRequestedOrientation(requestedOrientation);
		}
		super.setRequestedOrientation(requestedOrientation);
	}

	/**
	 * 顯示Alert
	 * 
	 * @param alertString
	 *            alert string
	 */
	public void showAlert(String alertString) {
		Builder MyAlertDialog = new AlertDialog.Builder(this);
		MyAlertDialog.setMessage(alertString);
		MyAlertDialog.setNeutralButton("OK", null);
		MyAlertDialog.show();
	}

	/**
	 * 顯示Alert，傳入OnClickListener參數， 設定使用者按下OK後執行的動作
	 * 
	 * @param alertString
	 *            alert string
	 * @param listener
	 *            設定使用者按下OK後執行的動作
	 */
	public void showAlert(String alertString, OnClickListener listener) {
		Builder MyAlertDialog = new AlertDialog.Builder(this);
		MyAlertDialog.setMessage(alertString);
		MyAlertDialog.setNeutralButton("OK", listener);
		MyAlertDialog.show();
	}

	/**
	 * 彈出有 YES , NO 的 POPUP
	 * 
	 * @param title
	 *            標題
	 * @param context
	 *            內容
	 * @param lestener
	 *            使用者按下後執行的動作
	 */
	public void showAlertWithTwoButton(String title, String context, OnClickListener lestener) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(title);
		alertDialog.setMessage(context);

		if (null != lestener) {
			alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, getText(android.R.string.ok), lestener);

			alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getText(android.R.string.cancel), lestener);
		}

		alertDialog.show();

	}

	/**
	 * 攔截BACK按鍵
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (null != myView) {
				if (myView.doOnBackKeyPress()) {
					return true;
				} else {
					return super.onKeyDown(keyCode, event);
				}
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 顯示Alert，使用者按下確定後結束Activity
	 * 
	 * @param alertString
	 */
	public void showAlertWithFinish(String alertString) {
		Builder MyAlertDialog = new AlertDialog.Builder(this);
		MyAlertDialog.setMessage(alertString);
		DialogInterface.OnClickListener OkClick = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}
		};
		MyAlertDialog.setNeutralButton("OK", OkClick);
		MyAlertDialog.show();
	}

	/**
	 * Alert 顯示 + Click -> 關閉Activity
	 * 
	 * @param alertString
	 */
	public void showAlertWithExit(String alertString) {
		Builder MyAlertDialog = new AlertDialog.Builder(this);
		MyAlertDialog.setMessage(alertString);
		DialogInterface.OnClickListener OkClick = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				System.exit(0);
			}
		};
		MyAlertDialog.setNeutralButton("OK", OkClick);
		MyAlertDialog.show();
	}

	/**
	 * 顯示轉圈圈
	 */
	public void showProgressDialog() {
		if (null != progressDialog && progressDialog.isShowing()) {
			return;
		}
		progressDialog = new ProgressDialog(this);
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setTitle(R.string.progress_title);
		try {
			progressDialog.show();
		} catch (Exception e) {

		}
	}

	/**
	 * 關閉轉圈圈
	 */
	public void hideProgressDialog() {
		if (null != progressDialog && progressDialog.isShowing()) {
			try {
				progressDialog.dismiss();
			} catch (Exception e) {

			}
		}
		progressDialog = null;
	}

	/**
	 * Menu 顯示
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	/**
	 * MEMU 按下後的事件
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		if (null != myView) {
			return myView.doOnOptionsItemSelected(item);
		} else {
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * 取得螢幕解析度
	 * 
	 * @return
	 */
	public int[] getDisplaySize() {
		DisplayMetrics dm = new DisplayMetrics();
		this.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int[] size = new int[2];
		size[0] = dm.widthPixels;
		size[1] = dm.heightPixels;
		return size;
	}

	/**
	 * 隱藏Soft keyboard
	 * 
	 * @param v
	 */
	public void keyboardHide(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

	/**
	 * 顯示Soft keyboard
	 * 
	 * @param v
	 */
	public void keyboardShow(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
	}

	/**
	 * Show toast
	 * 
	 * @param message
	 * @param time
	 */
	public void showToastMessage(String message, int time) {
		Toast.makeText(this, message, time).show();
	}

	/**
	 * Clear notification
	 */
	public void cleanNotifity() {
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		mNotificationManager.cancelAll();
	}

	/**
	 * 判斷是否有網路
	 * 
	 * @return
	 */
	public boolean hasInternet() {
		boolean result = false;
		ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connManager.getActiveNetworkInfo();
		if (info == null || !info.isConnected()) {
			result = false;
		} else {
			if (!info.isAvailable()) {
				result = false;
			} else {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 換頁（無過場動畫）
	 * 
	 * @param viewName
	 */
	public void openActivity(String viewName) {
		openActivity(viewName, false);
	}

	/**
	 * 換頁（無過場動畫）
	 * 
	 * @param viewName
	 */
	public void openActivity(String viewName, boolean finish) {
		openActivity(viewName, finish, Intent.FLAG_ACTIVITY_NEW_TASK);
	}

	/**
	 * 換頁（無過場動畫）
	 * 
	 * @param viewName
	 */
	public void openActivity(String viewName, boolean finish, int flag) {
		Intent intent = new Intent(this, MainActivity.class);
		intent.setFlags(flag | Intent.FLAG_ACTIVITY_NO_ANIMATION);
		intent.putExtra(BaseActivity.INTENT_KEY_VIEW_NAME, viewName);
		startActivity(intent);
		if (finish) {
			finish();
		}
	}
}
